yjx.service('LoginService', ['$rootScope', 'ipCookie', '$location', '$state', '$timeout', '$fetch', '$init', 'modalService', 'browserJudge', '$locals', 'urlCgService', 'detailService', 'wxShareService',
    function LoginService($rootScope, ipCookie, $location, $state, $timeout, $fetch, $init, modalService, browserJudge, $locals, urlCgService, detailService, wxShareService) {
        return {
            wxAutoLogin: function (url) {
                if (url != null && url.trim() != '' && url[0] != '/') {
                    url = '/' + url;
                }

                if ($rootScope.inviterUserId) {
                    url = url + '?inviteId=' + $rootScope.inviterUserId
                }
                if (!$rootScope.inviterUserId && $rootScope.identityTo == 1) {
                    url = url + '?identity=1'
                }
                // alert(url);
                // var token = 'oMNaqwAvoStG-3gRierTqTxrTVzU';
                var token = ipCookie('token');
                if (token) {
                    // wxLogin(url);
                    checkLogin(token, url);
                } else {
                    $init.cleanCookies();
                    wxLogin(url);
                }
            },
            /*从cookie中获取初始化数据*/
            getLoginData: function () {
                $rootScope.avatar = ipCookie('avatar');
                $rootScope.nickname = ipCookie('nickname');
                $rootScope.telephone = ipCookie('telephone');
                $rootScope.userId = ipCookie('Uid');
                $rootScope.user = ipCookie('user');
                $rootScope.digests = $rootScope.user ? $rootScope.user.digests : '';
            }
        }
        function wxLogin(url) {
            //登录授权后回调到选择身份登录页面
            url = url ? url : ''
            if (!$location.search().code && !$location.search().state && browserJudge.isWx()) {
                //alert('微信内部浏览器打开，直接验证授权');
                var firstRedirectUri = encodeURIComponent(
                    // 默认回调地址以https://开头;
                    // "https://www.aiekt.com/#/",
                    APPSRC + '#/',
                    // URL编码格式
                    "utf-8");
                var finalRedirectUri = encodeURIComponent(
                    // 以http:开头的被作为最终回调地址(可带？参数);   url参数以‘/’开头
                    APPSRC + '#' + url,
                    // URL编码格式
                    "utf-8");

                var wxLogin = "https://open.weixin.qq.com/connect/oauth2/authorize?"
                    // appid
                    + "appid=" + APPID
                    // redirect_uri
                    + "&redirect_uri=" + firstRedirectUri
                    // response_type
                    + "&response_type=code"
                    // scope
                    // + "&scope=snsapi_login"
                    + "&scope=snsapi_userinfo"
                    // state 参数，以http://开头将被作为最终回调地址(可带？参数);否则回到首页
                    //+ "&state=wxlogin"
                    + "&state=" + finalRedirectUri
                    // 结束标记（必传）
                    + "#wechat_redirect";
                // alert(wxLogin);
                self.location.href = wxLogin;
            }
        }
        function checkLogin(token, url) {
            $fetch.fetch(
                '/user/getInfo',
                {
                    params: {
                        identity: $rootScope.identityTo == 1 ? 'manager' : 'customer',
                    },
                    type: 'post',
                    cache: false,
                }
            ).then(function (data) {
                // alert(JSON.stringify(data))
                //这里的数据结构和登录的时候返回的不一样 
                // if(url.search(/teamNo\=/) > 0){
                //     $rootScope.teamJoin = true;
                // } 
                $init.initLoginData(data);
               
                $timeout(function () {
                    var absurl = DOMAIN + "/#" + url
                    // $init.initLoginUrl(absurl);
                    $rootScope.identity = $rootScope.identityTo;
                    if (data.state != -1) {
                        $timeout(function () {
                            if ((absurl && absurl.split('/#/') && absurl.split('/#/').length > 1) || (absurl && absurl.split('/') && absurl.split('/').length > 1)) {
                                urlCgService.encodeUrl(absurl);
                            } else {
                                $rootScope.showReady = true;
                                $state.go("index");
                            }
                        }, 500)
                    } else {
                        if($rootScope.teamJoin){
                            urlCgService.encodeUrl(absurl);
                        }else{
                            $rootScope.showReady = true;
                            detailService.openDetail('register');
                        }
                    }
                })
                $timeout(function () {
                    wxShareService.getConfig();
                })
            }).catch(function (e) {
                if (e.code == 2004) {
                    /*登录过期 重新授权*/
                    wxLogin(url);
                } else {
                    modalService.mainMsgError(e.msg);
                }

            })
        }

    }]);
